<template>
    <div>
        <el-row style="margin-top: 20px;">
          <el-col :span="6">
            <el-card shadow="always">
                <img :src="myInfo.photo" class="avatar"/>
                <el-upload
                    action="http://localhost:3030/user/upload/avatar/"
                    :headers="myHeaders"
                    :show-file-list="false" 
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                    <el-button type="info" style="width: 280px; margin-top: 10px;">更换头像</el-button>
                </el-upload>
            </el-card>
          </el-col>
          <el-col :span="16" :offset="1">
            <el-card shadow="hover">
                <el-tabs v-model="activeName" class="demo-tabs">
                    <el-tab-pane name="first">
                        <template #label>
                            <span class="custom-tabs-label">
                                <el-icon><FolderOpened /></el-icon>
                                <span>基本资料</span>
                            </span>
                        </template>
                        <el-form :model="myInfo">
                            <el-form-item label="用户名称">
                              <el-input v-model="myInfo.username" style="width: 20%;" />
                            </el-form-item>
                            <el-form-item label="用户状态">
                                <el-switch
                                    v-model="myInfo.status"
                                    disabled 
                                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                                    active-text="正常"
                                    inactive-text="禁用"
                                    inline-prompt
                                />
                            </el-form-item>
                            <el-form-item label="角色标识">
                                <el-tag v-if="myInfo.role === 'ROLE_ADMIN'" type="success">管理员</el-tag>
                                <el-tag v-else-if="myInfo.role === 'ROLE_BOSS'">负责人</el-tag>
                                <el-tag v-else-if="myInfo.role === 'ROLE_USER'" type="warning">普通用户</el-tag>
                                <el-tag v-else type="info">用户</el-tag>
                            </el-form-item>
                            <el-form-item label="联系方式">
                                <el-input v-model="myInfo.phone" style="width: 29%;" />
                              </el-form-item>
                            <el-form-item>
                              <el-button type="primary" @click="updatePersonal">确定</el-button>
                              <el-button>取消</el-button>
                            </el-form-item>
                          </el-form>
                    </el-tab-pane>
                    <el-tab-pane name="second">
                        <template #label>
                            <span class="custom-tabs-label">
                                <el-icon><Key/></el-icon>
                                <span>密码修改</span>
                            </span>
                        </template>
                        <el-form :model="EditPassWord" ref="formRef" label-position="right" label-width="80px" >
                            <el-form-item label="原密码" prop="oldPassword"
                                :rules="[{ required: true, message: '请输入原密码', trigger: 'blur' }]"
                            >
                              <el-input v-model="EditPassWord.oldPassword" show-password style="width: 30%;" />
                            </el-form-item>
                            <el-form-item label="新密码" prop="newPassword" 
                                :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]"
                            >
                                <el-input v-model="EditPassWord.newPassword" show-password style="width: 30%;" />
                            </el-form-item>
                            <el-form-item label="确认密码" prop="confirmPassword" 
                                :rules="[{ required: true, message: '请再次确认密码', trigger: 'blur' }]" >
                                <el-input v-model="EditPassWord.confirmPassword" show-password style="width: 30%;" />
                            </el-form-item>
                            <el-form-item>
                              <el-button type="primary" @click="updatePassword">确定</el-button>
                              <el-button @click="restForm()">取消</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                  </el-tabs>
            </el-card>
          </el-col>
        </el-row>
    </div>
</template>
<script>
    import {ref,reactive} from 'vue'
    import {useStore} from 'vuex'
    import {useRouter} from 'vue-router'
    import request from '@/utils/request'
    import {ElNotification,ElMessageBox,ElMessage} from 'element-plus'
    import { FolderOpened,Key } from '@element-plus/icons-vue'
    export default{
        name:'PersonalInfo',
        setup() {
            const store = useStore();
            const router = useRouter();
            const icon = {FolderOpened,Key}
            const myHeaders = ref({
                Authorization:"Bearer "+store.state.user.token
            })
            let activeName = ref('first')
            let myInfo = reactive({
                id:store.state.user.id,
                username:store.state.user.username,
                phone:store.state.user.phone,
                photo:store.state.user.photo,
                role:store.state.user.role,
                status:false
            })
            if(store.state.user.status === 'normal')
                myInfo.status = true
            else
                myInfo.status = false
            //密码修改
            let EditPassWord = reactive({
                oldPassword:'',
                newPassword:'',
                confirmPassword:'',
            })
            let formRef = ref(null)
            //上传头像成功
            let handleAvatarSuccess = (resp) => {
                myInfo.photo = 'http://localhost:3030' + resp.avatarUrl;
                updateUserAvatar()
            }
            let updateUserAvatar = () => {
                request({
                    url:'/personal/update/avatar/',
                    method:'get',
                    params:{
                        id:store.state.user.id,
                        photo:myInfo.photo
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        ElNotification({title: '头像上传成功！',type: 'success',})
                    }
                    getUserById()
                }).catch(() => {});
            }
            let getUserById = () => {
                request({
                    url:'/personal/get/byId/',
                    method:'get',
                    params:{
                        id:store.state.user.id
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.status === true) resp.status = 'normal';
                    else resp.status = 'stop';
                    store.commit('getLoginUser',resp)
                }).catch(() => {});
            }
            getUserById()
            let beforeAvatarUpload = () => {
            }
            let updatePersonal = () => {
                request({
                    url:'/personal/update/info/',
                    method:'post',
                    data:{
                        id:store.state.user.id,
                        username:myInfo.username,
                        phone:myInfo.phone,
                    },
                    headers:{
                        Authorization:"Bearer "+store.state.user.token,
                    }
                }).then((resp) => {
                    if(resp.message === 'success'){
                        ElNotification({title: '修改成功！',type: 'success',})
                    }else if(resp.message === 'repeat'){
                        ElNotification({title: '用户名重复！',type: 'error',})
                    }
                    getUserById()
                }).catch(() => {});
            }
            let updatePassword = () => {
                formRef.value.validate((valid) => {
                    if(valid){
                        console.log("通过")
                        request({
                            url:'/personal/update/password/',
                            method:'post',
                            data:{
                                id:store.state.user.id,
                                ...EditPassWord
                            },
                            headers:{
                                Authorization:"Bearer "+store.state.user.token,
                            }
                        }).then((resp) => {
                            if(resp.message === 'success'){
                                ElMessageBox.alert('<h3>用户密码修改成功！请重新登录！</h3>',{
                                    dangerouslyUseHTMLString: true,
                                    confirmButtonText: '确认',
                                    showClose:false,
                                    draggable: true,
                                    type: 'warning',
                                    callback:() => {
                                        ElMessage({
                                            message: '退出成功!',
                                            grouping: true,
                                            type: 'warning',
                                        })
                                        store.commit('Logout');
                                        localStorage.removeItem('jwt_token');
                                        router.push({
                                            path:'/login'
                                        })
                                    }
                                })
                            }else if(resp.message === 'old_error'){
                                ElNotification({title: '修改失败！',message:'原密码错误!',type: 'error',})
                            }else if(resp.message === 'confirm_error'){
                                ElNotification({title: '修改失败！',message:'两次输入密码不一致!',type: 'error',})
                            }
                        }).catch(() => {});
                    }else{
                        console.log("未通过")
                        return false;
                    }
                })
            }
            let restForm = () => {
                formRef.value.resetFields();
            }
            return {
                ...icon,
                myInfo,
                myHeaders,
                activeName,
                EditPassWord,
                handleAvatarSuccess,
                beforeAvatarUpload,
                formRef,
                restForm,
                updatePersonal,
                updatePassword,
            }
        },
    }
</script>
<style scoped> 
.avatar {
  width: 100%;
  height: 275px;
  border: 8px solid #D4D7DE;
  box-sizing: border-box;
}
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.demo-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}
.demo-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}
</style>